//拦截器
import axios from 'axios'
import { Dialog } from 'vant'

const STATUS_CODE_MAP = new Map([
    [400,'错误请求'],
    [401,'未授权 请重新登录'],
    [403,'拒绝访问'],
    [404,'请求错误，没找到资源'],
    [405,'请求方法未允许'],
    [408,'请求超时'],
    [500,'服务器端出错'],
    [501,'网络未实现'],
    [502,'网络错误'],
    [503,'错误请求'],
    [504,'网络超时'],
    [505,'http版本不支持请求']
])


class HttxError extends Error {
	constructor(message) {
		super(message);
		this.name = this.constructor.name;
	}
}
class HttxStatusError extends HttxError {
	constructor(message, statusCode, dataResult) {
		super(message);
		this.name = this.constructor.name;
		this.statusCode = statusCode;
		this.dataResult = dataResult;
	}
}


//创建实例
const service = axios.create({
    timeout:30*1000
})

//请求拦截器
service.interceptors.request.use(config=>{
    config.headers = config.headers || {
        'content-type': 'application/x-www-form-urlencoded',
    }
    let token = weixin.getToken()

    if(token){
        config.headers['token'] = '' + token
        config.headers['Authorization'] = '' + token
    }

    return config
},error=>{
    Promise.reject(error)
})

//响应拦截
service.interceptors.response.use(response => {
    
    return response
}, error => {
    
    let statusCode = error.response.status;
    let dataResult = error.response.data;

    try {
        if (statusCode >= 500) {// 5xx
            throw new HttxStatusError('系统错误', statusCode, dataResult);
        } else if (statusCode >= 400) {// 4xx
            throw new HttxStatusError('请求出错', statusCode, dataResult);
        }
        throw new Error(`Unsupported statusCode ${statusCode}`);
    } catch (error2) {
        handleError(error2);
    }
})


function handleError(error) {
	if (error instanceof HttxStatusError) {
		let statusCode = error.statusCode;
		let dataResult = error.dataResult;
		if (statusCode == 401) {
            weixin.login(); //请先登录
		} else {
			let msg;
			if (Object.prototype.toString.call(dataResult) === '[object Object]') {
				msg = dataResult.msg;
			}
			msg = msg || STATUS_CODE_MAP.get(statusCode) || error.message;
            Dialog({message:msg})
			console.log(msg);
		}
	} else if (error instanceof Error) {
        Dialog({message:error.message})
		console.log(error.message);
	} else {
        Dialog({message:error})
		console.log(error);
	}

	throw error;
}


export default service